package com.ruoyi.system.service.impl;

import java.util.HashMap;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;

import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.LeaveapplyMapper;
import com.ruoyi.system.domain.Leaveapply;
import com.ruoyi.system.service.ILeaveapplyService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 请假Service业务层处理
 * 
 * @author shenzhanwang
 * @date 2022-04-02
 */
@Service
@Transactional
public class LeaveapplyServiceImpl implements ILeaveapplyService 
{
    @Resource
    private LeaveapplyMapper leaveapplyMapper;

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private TaskService taskService;

    @Resource
    IdentityService identityService;

    @Resource
    HistoryService historyService;

    /**
     * 查询请假
     * 
     * @param id 请假主键
     * @return 请假
     */
    @Override
    public Leaveapply selectLeaveapplyById(Long id)
    {
        return leaveapplyMapper.selectLeaveapplyById(id);
    }

    /**
     * 查询请假列表
     * 
     * @param leaveapply 请假
     * @return 请假
     */
    @Override
    public List<Leaveapply> selectLeaveapplyList(Leaveapply leaveapply)
    {
        return leaveapplyMapper.selectLeaveapplyList(leaveapply);
    }

    /**
     * 新增请假
     * 
     * @param leaveapply 请假
     * @return 结果
     */
    @Override   // 代码总结
    public int insertLeaveapply(Leaveapply leaveapply)
    {
        int rows = leaveapplyMapper.insertLeaveapply(leaveapply);

        // 1.消息启动事件
        identityService.setAuthenticatedUserId(leaveapply.getUserId());

        // 2.启动流程实例
        HashMap<String, Object> variables = new HashMap<>();    // 储存要传给流程引擎的变量
        variables.put("applyuserid", leaveapply.getUserId());   // 添加流程变量（键值对）
        variables.put("deptleader", leaveapply.getDeptleader());
        runtimeService.startProcessInstanceByKey("leave", String.valueOf(leaveapply.getId()), variables);// 启动流程实例（流程key, 业务key（主键）, 传入变量）

        // 3.查询任务（在请假审批中第一个节点，申请人自己提交只有一个Task任务）
        Task autoTask = taskService.createTaskQuery()   // 查询当前任务（代办节点）
                .processDefinitionKey("leave")  // 限定查询流程定义key
                .processInstanceBusinessKey(String.valueOf(leaveapply.getId()))  // 业务key（主键）
                .singleResult();    // 只获取一个任务对象（节点）

        // 4.完成任务
        taskService.complete(autoTask.getId());
        return rows;
    }

    /**
     * 修改请假
     * 
     * @param leaveapply 请假
     * @return 结果
     */
    @Override
    public int updateLeaveapply(Leaveapply leaveapply)
    {
        return leaveapplyMapper.updateLeaveapply(leaveapply);
    }

    /**
     * 批量删除请假
     * 
     * @param ids 需要删除的请假主键
     * @return 结果
     */
    @Override
    public int deleteLeaveapplyByIds(String ids)
    {
        String[] keys = Convert.toStrArray(ids);    // 将传入的逗号分隔 ID 字符串转成数组

        for (String key : keys) {   // 增强for循环keys值一次赋值给key

            // 1.删除流程实例
            ProcessInstance process = runtimeService.createProcessInstanceQuery()   // 查询当前流程实例（正在运行的流程）
                    .processDefinitionKey("leave")  // 限定查询流程定义key
                    .processInstanceBusinessKey(key)  // 业务key（主键）
                    .singleResult();    // 只获取一个流程实例对象
            if (process != null) {
                runtimeService.deleteProcessInstance(process.getId(), "删除");
            }

            // 2.删除历史数据
            HistoricProcessInstance history = historyService.createHistoricProcessInstanceQuery()   // 查询历史流程实例（已经结束的流程）
                    .processDefinitionKey("leave")
                    .processInstanceBusinessKey(key)
                    .singleResult();
            if (history != null){
                historyService.deleteHistoricProcessInstance(history.getId());
            }
            leaveapplyMapper.deleteLeaveapplyById(Long.parseLong(key));
        }
        return keys.length;
    }

    /**
     * 删除请假信息
     * 
     * @param id 请假主键
     * @return 结果
     */
    @Override
    public int deleteLeaveapplyById(Long id)
    {
        return leaveapplyMapper.deleteLeaveapplyById(id);
    }
}
